require 'net/http'
require 'CGI'

class MALHandler
  
  attr_accessor :user, :password, :http, :cookie, :headers

	def initialize(params)
	  @user = params[:user]
	  @password = params[:password]
	  @http = http = Net::HTTP.new('myanimelist.net', 80)
	  
	  headers = {
      'Referer' => 'http://myanimelist.net',
      'Content-Type' => 'application/x-www-form-urlencoded'
    }
    resp = @http.post('/login.php', 'username='+CGI::escape(@user)+'&password='+CGI::escape(@password)+'&cookie=true',headers)
    cookieY = resp.response['set-cookie'].split(', ')[0].split('; ')[0]
    cookieZ = resp.response['set-cookie'].split(', ')[2].split('; ')[0]
    @cookie = cookieY+"; "+cookieZ

    @headers = {
      'Cookie' => @cookie,
      'Content-Type' => 'application/x-www-form-urlencoded',
    }
  end
  
  def set(params)
    if params.has_key? :series_id and params.has_key? :ep_val
      @http.post('/includes/change_ep.php', 'series_id='+CGI::escape(params[:series_id])+'&ep_val='+CGI::escape(params[:ep_val]), @headers)
    end
    if params.has_key? :anime_id and params.has_key? :ep_val
      @http.post('/includes/ajax.inc.php?t=79', 'anime_id='+CGI::escape(params[:anime_id])+'&ep_val='+CGI::escape(params[:ep_val]), @headers)
    end
  end
  
  def get(params)
    if params.has_key? :resource
      return @http.get(params[:resource], @headers).body
    end
    if params.has_key? :title
      doc, animes = REXML::Document.new(self.get(:resource => '/malappinfo.php?u=' + @user))
      doc.elements.each('myanimelist/anime') do |anime|
        if anime.elements['series_title'].text.index(params[:title]) or anime.elements['series_synonyms'].text.index(params[:title])
          return anime.elements['series_animedb_id'].text.to_i
        end
      end #enddo
      return nil # anime not found in your list
    end #endif
  end #enddef
  
end
